
<template>
  <div class="app-container">
    <div class="filter-container">
      <el-radio-group v-model="radio1" @change="change">
        <el-radio-button label="1">标题筛选</el-radio-button>
        <el-radio-button label="2">生成队列</el-radio-button>

      </el-radio-group>

      <el-button v-show="radio1==2" style="margin-left:10px;" type="primary" @click="reCreate">
        重新生成
      </el-button>

      <el-button v-show="radio1==2" type="danger" style="margin-left:10px;" @click="handleDeleteAll()">
        {{ $t('table.delete') }}
      </el-button>
    </div>

    <!-- 标题筛选 -->
    <div v-show="radio1 == 1">
      <div class="filter-container">

        <el-button style="margin-right:5px;" type="primary" @click="handleCreate">
          关键词添加
        </el-button>
        <el-select
          v-model="dataRepresentationValue"
          :popper-class="'mySelect'"
          :multiple="true"
          collapse-tags
        >
          <el-option
            v-for="(item, i) in dataRepresentation"
            :key="item.label"
            :label="item.label"
            :value="item.id"
          >
            <!--  dom结构区域 -->
            <div class="box">
              <el-row>
                <el-col :span="3" class="page-lv3-title" @click.stop.native>{{
                  item.label
                }}</el-col>
                <el-col :span="21" style="text-align: right">
                  <el-button
                    class="custom"
                    :type="item.buttonShow === 1 ? 'primary' : 'text'"
                    @click.stop="rangeSelection(null, null, 1, i)"
                  >不限</el-button>

                  <el-button
                    class="custom"
                    :type="item.buttonShow === 2 ? 'primary' : 'text'"
                    @click.stop="rangeSelection(0, 100, 2, i)"
                  >&lt;100</el-button>
                  <el-button
                    class="custom"
                    :type="item.buttonShow === 3 ? 'primary' : 'text'"
                    @click.stop="rangeSelection(100, 1000, 3, i)"
                  >100-1k</el-button>
                  <el-button
                    class="custom"
                    :type="item.buttonShow === 4 ? 'primary' : 'text'"
                    @click.stop="rangeSelection(1000, 10000, 4, i)"
                  >1k-1w</el-button>
                  <el-button
                    class="custom"
                    :type="item.buttonShow === 5 ? 'primary' : 'text'"
                    @click.stop="rangeSelection(10000, 100000, 5, i)"
                  >1w-10w</el-button>
                  <el-button
                    class="custom"
                    :type="item.buttonShow === 6 ? 'primary' : 'text'"
                    @click.stop="rangeSelection(100000, null, 6, i)"
                  >&gt;10w</el-button>
                  <el-button
                    :type="item.buttonShow === 7 ? 'primary' : 'text'"
                    class="custom"
                    @click.stop="rangeSelection(null, null, 7, i)"
                  >自定义</el-button>

                </el-col>

              </el-row>
              <el-row
                v-show="item.buttonShow === 7 && item.customShow"
                class="input-box"
              >
                <el-col :span="8">
                  <el-input
                    v-model.number.trim="filterConfig.dataRepresentation[i].min"
                    @click.stop.native
                  />
                </el-col>
                <el-col :span="2" style="text-align: center">
                  <div>to</div>
                </el-col>
                <el-col :span="8">
                  <el-input
                    v-model.number.trim="filterConfig.dataRepresentation[i].max"
                    @click.stop.native
                  />
                </el-col>
                <el-col :span="6">
                  <el-button
                    class="custom"
                    @click.stop="onRefreshInput(i)"
                  >重置</el-button><el-button
                    v-show="false"
                    type="primary"
                    class="custom"
                    @click.stop="customConfirm(i)"
                  >确定</el-button>
                </el-col>
              </el-row>
            </div>

          </el-option>
        </el-select>

        <el-button style="margin-left:5px;" type="primary" @click="openItem()">
          生成
        </el-button>

      </div>
      <el-table
        :key="tableKey"
        v-loading="listLoading"
        :data="titleList"
        border
        fit
        highlight-current-row
        style="width: 100%;"
        @selection-change="handleSelectionChange"
      >
        <el-table-column
          type="selection"
          width="55"
        />
        <el-table-column :label="$t('table.id')" prop="id" align="center" width="80" :class-name="getSortClass('id')">
          <template slot-scope="{row}">
            <span>{{ row.id }}</span>
          </template>
        </el-table-column>
        <el-table-column label="标题名称" min-width="150px">
          <template slot-scope="{row}">
            <el-input v-model="row.title" placeholder="请输入标题名称" class="filter-item" />
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 生成队列 -->
    <div v-show="radio1 == 2">
      <div class="filter-container">
        <!-- <el-input v-model="listQuery.title" placeholder="请输入名称" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter" />

        <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
          {{ $t('table.search') }}
        </el-button> -->

        <!-- <el-button class="filter-item" type="primary" icon="el-icon-edit" @click="handleCreate">
          {{ $t('table.add') }}
        </el-button> -->

      </div>
      <el-table
        :key="tableKey"
        v-loading="listLoading"
        :data="list"
        border
        fit
        highlight-current-row
        style="width: 100%;"
        @selection-change="handleSelectionChange2"
      >
        <el-table-column
          type="selection"
          width="55"
        />
        <el-table-column label="ID" prop="id" align="center" width="180">
          <template slot-scope="{row}">
            <span>{{ row.article_id }}</span>
          </template>
        </el-table-column>
        <el-table-column label="标题" min-width="150px">
          <template slot-scope="{row}">
            <span class="link-type">{{ row.title }}</span>
          </template>
        </el-table-column>
        <el-table-column label="状态" min-width="150px">
          <template slot-scope="{row}">
            <el-tag v-if="row.is_fabu==1">
              生成中
            </el-tag>
            <el-tag v-if="row.is_fabu==2">
              可发布
            </el-tag>
            <el-tag v-if="row.is_fabu==3">
              发布
            </el-tag>
          </template>
        </el-table-column>

        <!-- <el-table-column :label="$t('table.actions')" align="center" width="230" class-name="small-padding fixed-width">
          <template slot-scope="{row,$index}">
            <el-button type="primary" size="mini" @click="handleUpdate(row)">
              {{ $t('table.edit') }}
            </el-button>
            <el-button v-if="row.status!='deleted'" size="mini" type="danger" @click="handleDelete(row,$index)">
              {{ $t('table.delete') }}
            </el-button>
          </template>
        </el-table-column> -->
      </el-table>

      <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />
    </div>

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="100px" style="width: 400px; margin-left:50px;">
        <el-form-item label="输入关键词" prop="gjc">
          <el-input v-model="temp.gjc" />
        </el-form-item>
        <el-form-item label="数量" prop="qty">
          <el-input v-model.number="temp.qty" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          {{ $t('table.cancel') }}
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
          {{ $t('table.confirm') }}
        </el-button>
      </div>
    </el-dialog>

    <el-dialog :visible.sync="dialogPvVisible" title="Reading statistics">
      <el-table :data="pvData" border fit highlight-current-row style="width: 100%">
        <el-table-column prop="key" label="Channel" />
        <el-table-column prop="pv" label="Pv" />
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="dialogPvVisible = false">{{ $t('table.confirm') }}</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { getwzlist, fetchPv, updateArticle, gjc, getwz, scwz, unlink } from '@/api/article'
import waves from '@/directive/waves' // waves directive
import { parseTime } from '@/utils'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import { getToken } from '@/utils/auth'
const calendarTypeOptions = [
  { key: 'CN', display_name: 'China' },
  { key: 'US', display_name: 'USA' },
  { key: 'JP', display_name: 'Japan' },
  { key: 'EU', display_name: 'Eurozone' }
]

// arr to obj, such as { CN : "China", US : "USA" }
const calendarTypeKeyValue = calendarTypeOptions.reduce((acc, cur) => {
  acc[cur.key] = cur.display_name
  return acc
}, {})

export default {
  name: 'CreateArticle',
  components: { Pagination },
  directives: { waves },
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: 'success',
        draft: 'info',
        deleted: 'danger'
      }
      return statusMap[status]
    },
    typeFilter(type) {
      return calendarTypeKeyValue[type]
    }
  },
  data() {
    return {
      multipleSelection: [],
      multipleSelection2: [],
      dataRepresentationValue: [1, 2],
      dataRepresentation: [
        {
          label: '文章数',
          id: 1,
          customShow: false, // 自定义输入框显示隐藏
          buttonShow: 1 // 文字按钮与默认按钮切换
        },
        {
          label: '图片数',
          id: 2,
          customShow: false,
          buttonShow: 1
        }
      ],
      filterConfig: {
        dataRepresentation: [
          {
            type: 1,
            min: null,
            max: null
          },
          {
            type: 2,
            min: null,
            max: null
          }

        ]
      },
      // titleList: [{
      //   'id': 0,
      //   'title': '北京新地标亮相，现代与古典融合，成为网红打卡新热点！',
      //   'time': '2024-06-13 23-10-10',
      //   'status': 0,
      //   'userid': '2',
      //   'article_id': '22024061323101021'
      // }],
      titleList: [],
      radio1: '2',

      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 10,
        importance: undefined,
        title: undefined,
        type: undefined,
        sort: '+id'
      },
      importanceOptions: [1, 2, 3],
      calendarTypeOptions,
      sortOptions: [{ label: 'ID Ascending', key: '+id' }, { label: 'ID Descending', key: '-id' }],
      statusOptions: ['published', 'draft', 'deleted'],
      showReviewer: false,
      temp: {
        qty: null,
        gjc: '',
        userid: ''
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: 'Edit',
        create: '生成标题'
      },
      dialogPvVisible: false,
      pvData: [],
      rules: {
        type: [{ required: true, message: 'type is required', trigger: 'change' }],
        timestamp: [{ type: 'date', required: true, message: 'timestamp is required', trigger: 'change' }],
        gjc: [{ required: true, message: 'title is required', trigger: 'blur' }],
        qty: [{ required: true, message: 'num is required', trigger: 'blur' }]
      },
      downloadLoading: false
    }
  },
  created() {
    this.getList()
    setTimeout(() => {
      this.listLoading = false
    }, 1.5 * 1000)
  },
  methods: {
    // 重新生成文章
    reCreate() {
      if (this.multipleSelection2.length === 0) {
        this.$notify({
          title: '提示',
          message: '请选择文章',
          type: 'success',
          duration: 2000
        })
        return
      }
      this.multipleSelection2.forEach((item) => {
        const data = {
          data: [{
            title: item.title,
            article_id: item.article_id
          }],
          user_id: getToken()
        }
        this.getwz(data)
      })
      this.openFullScreen2()
      setTimeout(() => {
        this.radio1 = '2'
        this.getList()
      }, 2000)
    },
    handleDeleteAll() {
      if (this.multipleSelection2.length > 0) {
        this.handleDelete(this.multipleSelection2)
      } else {
        this.$notify({
          title: '提示',
          message: '请选择文章',
          type: 'success',
          duration: 2000
        })
      }
    },
    change(e) {
      if (e === '2') {
        this.getList()
      }
    },
    // 生成文章
    openItem() {
      this.multipleSelection.forEach((item) => {
        const data = {
          data: [{
            title: item.title,
            article_id: item.article_id
          }],
          user_id: getToken()
        }
        this.getwz(data)
      })
      this.openFullScreen2()
      setTimeout(() => {
        this.radio1 = '2'
        this.getList()
      }, 2000)
    },
    openFullScreen2() {
      const loading = this.$loading({
        lock: true,
        text: 'Loading',
        spinner: 'el-icon-loading',
        background: 'rgba(255, 255, 255, 0.7)'
      })
      setTimeout(() => {
        loading.close()
      }, 2000)
    },
    /**
     * min 最小值 max 最大值 show 按钮样式切换 i 元素下标
     */
    rangeSelection(min, max, show, i) {
      this.dataRepresentation[i].buttonShow = show
      this.dataRepresentation[i].customShow = true
      this.filterConfig.dataRepresentation[i].min = min
      this.filterConfig.dataRepresentation[i].max = max
    },
    // 打开自定义输入框
    customConfirm(i) {
      this.dataRepresentation[i].customShow = true
    },
    // 重制输入框
    onRefreshInput(i) {
      this.filterConfig.dataRepresentation[i].min = null
      this.filterConfig.dataRepresentation[i].max = null
    },

    getList() {
      this.listLoading = true
      getwzlist({ user_id: getToken(), is_fabu: 1 }).then(response => {
        this.list = response.data
        // this.total = response.data.total
        this.listLoading = false
      })
      // fetchList(this.listQuery).then(response => {
      //   this.list = response.data.items
      //   this.total = response.data.total

      //   // Just to simulate the time of the request
      //   setTimeout(() => {
      //     this.listLoading = false
      //   }, 1.5 * 1000)
      // })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    sortChange(data) {
      const { prop, order } = data
      if (prop === 'id') {
        this.sortByID(order)
      }
    },
    sortByID(order) {
      if (order === 'ascending') {
        this.listQuery.sort = '+id'
      } else {
        this.listQuery.sort = '-id'
      }
      this.handleFilter()
    },
    resetTemp() {
      this.temp = {
        qty: null,
        gjc: '',
        userid: ''
      }
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    handleSelectionChange(val) {
      console.log({ val })
      this.multipleSelection = val
    },
    handleSelectionChange2(val) {
      console.log({ val })
      this.multipleSelection2 = val
    },
    gjc() {
      this.listLoading = true
      this.dialogFormVisible = false
      this.temp.userid = getToken()
      gjc(this.temp).then((res) => {
        const list = res.data
        const arr = []
        list.forEach((item, index) => {
          arr.push({ id: index, title: item[0], time: item[1], status: item[2], userid: item[3], article_id: item[4] })
        })
        this.titleList = arr
        this.$notify({
          title: '成功',
          message: '创建成功',
          type: 'success',
          duration: 2000
        })

        this.listLoading = false
        console.log({ res })
      })
    },
    getwz(data) {
      getwz(data).then((res) => {
        setTimeout(() => {
          this.getList()
        }, 500)
      })
    },
    createData() {
      // console.log(555); return
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.gjc()
          // this.temp.id = parseInt(Math.random() * 100) + 1024 // mock a id
          // this.temp.author = 'vue-element-admin'
          // createArticle(this.temp).then(() => {
          //   this.list.unshift(this.temp)
          //   this.dialogFormVisible = false
          //   this.$notify({
          //     title: '成功',
          //     message: '创建成功',
          //     type: 'success',
          //     duration: 2000
          //   })
          // })
        }
      })
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row) // copy obj
      this.temp.timestamp = new Date(this.temp.timestamp)
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          tempData.timestamp = +new Date(tempData.timestamp) // change Thu Nov 30 2017 16:41:05 GMT+0800 (CST) to 1512031311464
          updateArticle(tempData).then(() => {
            const index = this.list.findIndex(v => v.id === this.temp.id)
            this.list.splice(index, 1, this.temp)
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '更新成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    unlink(path) {
      unlink({ path })
    },
    handleDelete(row) {
      const data = row.map((item) => {
        const { article_id, content } = item
        return { article_id, content: '' }
      })
      scwz(data).then(response => {
        if (response.code === 200) {
          // 删除本地文件
          data.forEach((item) => {
            const name = item.article_id + '.docx'
            this.unlink(this.dir + '//' + name)
          })

          this.$notify({
            title: '成功',
            message: '删除成功',
            type: 'success',
            duration: 2000
          })
          this.getList()
        } else {
          this.$notify({
            title: '失败',
            message: '删除失败',
            type: 'error',
            duration: 2000
          })
        }
      })
    },
    handleFetchPv(pv) {
      fetchPv(pv).then(response => {
        this.pvData = response.data.pvData
        this.dialogPvVisible = true
      })
    },
    handleDownload() {
      this.downloadLoading = true
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = ['timestamp', 'title', 'type', 'importance', 'status']
        const filterVal = ['timestamp', 'title', 'type', 'importance', 'status']
        const data = this.formatJson(filterVal)
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: 'table-list'
        })
        this.downloadLoading = false
      })
    },
    formatJson(filterVal) {
      return this.list.map(v => filterVal.map(j => {
        if (j === 'timestamp') {
          return parseTime(v[j])
        } else {
          return v[j]
        }
      }))
    },
    getSortClass: function(key) {
      const sort = this.listQuery.sort
      return sort === `+${key}` ? 'ascending' : 'descending'
    }
  }
}
</script>
<style>
</style>
<style scoped>
.el-select-dropdown__item{

  height: auto !important;

}
</style>

